#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:8_generate_ip_file_and_count_ip_frequency.py
# author:张世航
# datetime:2024/11/9 22:29
# software: PyCharm
"""
this is function  description 
"""
# import module your need


# 8 京东二面笔试题
# 1） 生成一个大文件ip.txt,要求1200行，每行随机为172.25.254.1---172.25.254.254之间的一个ip地址;
# 2） 读取ip.txt文件统计这个文件中ip出现频率排前10的ip

import random
from collections import Counter

def generate_ip_file(filename, lines=1200):
    """生成随机 IP 文件"""
    with open(filename, "w") as f:
        for _ in range(lines):
            ip = f"172.25.{random.randint(0, 254)}.{random.randint(0, 254)}"
            f.write(ip + "\n")

def count_ip_frequency(filename):
    """统计 IP 出现频率"""
    with open(filename, "r") as f:
        ips = f.readlines()
    ip_counts = Counter(ip.strip() for ip in ips)  # 统计 IP 频率
    return ip_counts.most_common(10)  # 返回出现频率前10的 IP

# 生成 IP 文件
generate_ip_file("ip.txt")

# 统计 IP 频率
top_ips = count_ip_frequency("ip.txt")
print("出现频率前10的IP：", top_ips)